#include "porting.h"
#include "fileio.h"
#include "lnthread.h"
#include "errorcode.h"

#include <stdio.h>

#ifdef WINDOWS

char* read_file (
    const char * file_name,
    struct respool_t * pool,
    int* size )
{
  HANDLE hF;
  DWORD dwReadSize;
  char* buf;

  hF = CreateFileA (file_name, GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, 0,NULL);

  if (hF == INVALID_HANDLE_VALUE)
  {
    er_set (NULL, LN_ER_FILE_OPEN_FAILED, file_name, "r");
    return NULL;
  };

  *size = GetFileSize (hF, NULL);
  
  buf = respool_alloc (pool, *size + sizeof(void*));
  
  if (buf == NULL)
  {
    goto cleanup;
  };

  if ( FALSE == ReadFile (hF, buf, *size, &dwReadSize, NULL) )
  {
    er_set (NULL, LN_ER_FILE_READ_ERROR, file_name, *size);
    buf = NULL;
    goto cleanup;
  }

  buf[*size] = 0;
  buf[*size + 1] = 0;

cleanup:;

  if (hF != INVALID_HANDLE_VALUE)
  {
    CloseHandle (hF);
  };

  return buf;
}

#endif


char** read_lines (
  const char * file_name,
  struct respool_t * pool)
{
  int size,cnt;
  char *buffer, *p, **lines;

  buffer = read_file (file_name, pool, &size);

  if (buffer == NULL)
  {
    return NULL;
  };

  for (cnt =0, p = buffer; *p; p++ )
  {
    if ( *p=='\r' && p[1] == '\n' )
    {
      p++;
      cnt++;
    } 
    else if (*p == '\n')
    {
      cnt++;
    }
  };

  lines = (char**) respool_alloc (pool, sizeof(void*) * ( cnt + 2 ) );

  if (lines == NULL)
  {
    return NULL;
  }

  for (cnt =0, p = buffer; *p; )
  {
    lines[cnt++] = p;

    while (*p && *p != '\n')
    {
      p++;
    };

    if (*p == '\n' && ( p == buffer || (p > buffer && p[-1]=='\r') ) )
    {
      p[-1] = 0;
    }

    *(p++) = 0;
  };

  lines[cnt] = (void*)0;

  return lines;
}

int write_lines (
   const char* file_name,
   char** lines )
{
  FILE* fd;

  fd = fopen (file_name,"w");

  if (fd == NULL)
  {
    er_set (NULL, LN_ER_FILE_OPEN_FAILED, file_name,"w");
    return LN_ER_FILE_OPEN_FAILED;
  };

  for ( ;*lines; lines++)
  {
    fputs (*lines, fd);
    fputs (FILE_CRLF, fd);
  };

  fclose (fd);

  return 0;
};

